<?php

namespace app\common\model;

use think\Model;
use app\common\model\Stand;

class Finance extends Model
{

    

    

    // 表名
    protected $name = 'finance';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text'
    ];
    

    
    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2')];
    }



    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 添加数据
     * @return void
     */
    public static function addData($data,$type)
    {
        $insert = [];
        $insert['stand_id'] = $data['stand_id'];
        $insert['price'] = $data['price'];
        $insert['type'] = $type;
        $insert['product'] = $data['product'];
        $insert['num'] = isset($data['num']) ? $data['num'] : 1;
        $insert['unit_price'] = isset($data['unit_price']) ? $data['unit_price'] : 0;
        $insert['remark'] = isset($data['remark']) ? $data['remark'] : '';
        $insert['createtime'] = time();
        $stand = Stand::get($data['stand_id']);
        if($type == 1){//收入
            $stand->profit = $stand->profit + $data['price'];
        }else{
            $stand->profit = $stand->profit - $data['price'];
        }
        $stand->save();
        self::create($insert);
    }


    public function stand()
    {
        return $this->belongsTo('Stand', 'stand_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
